<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    vDOM演示
    <script>
        const vdom = {
          type: "div",
          props: {
            class: "container",
          },
          children: [
            {
              type: "h1",
              props: {},
              children: ["虚拟DOM演示"],
            },
            {
              type: "p",
              props: {
                style: "color: blue",
              },
              children: ["这是一个段落"],
            },
            {
              type: "ul",
              props: {},
              children: [
                {
                  type: "li",
                  props: {},
                  children: ["项目1"],
                },
                {
                  type: "li",
                  props: {},
                  children: ["项目2"],
                },
                {
                  type: "li",
                  props: {},
                  children: ["项目3"],
                },
              ],
            },
          ],
        };


      // 将虚拟DOM转换为真实DOM的函数
      function render(vnode) {
        // 如果是文本节点,直接创建文本节点
        if (typeof vnode === "string" || typeof vnode === "number") {
          return document.createTextNode(vnode);
        }
        // 创建元素
        const element = document.createElement(vnode.type);
        // 设置属性
        for (let key in vnode.props) {
          element.setAttribute(key, vnode.props[key]);
        }
        // 递归渲染子节点
        vnode.children.forEach((child) => {
          element.appendChild(render(child));
        });
        return element;
      }
      // 渲染到页面
      const rootElement = render(vdom);
      document.body.appendChild(rootElement);
    </script>
  </body>
</html>
